
#include "usart.h"
volatile uint8_t incomingchar = 0;
void usart_init()
{
	uint8_t baud;
	baud = 25;

	/* Set baud rate */
	UBRRH = (unsigned char)(baud>>8);
	UBRRL = (unsigned char)baud;

	/* Enable receiver, transmitter, and receive complete interrupt */
	UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);

	/* Set frame format: 8data, 1stop bit*/
	UCSRC = (1<<URSEL)|(0<<USBS)|(3<<UCSZ0);
    
    usart_echo = 1; //echo to terminal ON
    memset(usart_buffer, 0, USART_BUFFER_SIZE+1);
}
void usart_run(void)
{
	if(incomingchar)
	{
		signal(uart_char_event, &uc, 1);
		incomingchar = 0;
	}
	
}
// Read Interrupt
ISR(USART_RXC_vect)
{
    uc = usart_read();
	incomingchar = 1;
    if (usart_readline)
    {
        //flush previous stuff and start over when full
        if(usart_buffer_index > USART_BUFFER_SIZE)
        {
            usart_readln_start();
        }
        if (uc != 012 && uc != 015)
        {
            usart_buffer[usart_buffer_index] = uc;
            usart_buffer_index++;
        }
        else
        {
            usart_buffer[usart_buffer_index] = '\0';
            usart_readln_ready();
        }
    }
}

void usart_transmit(uint8_t data)
{
	/* Wait for empty transmit buffer */
	while ( !( UCSRA & (1<<UDRE)) );
	/* Put data into buffer, sends the data */
	UDR = data;
}

void usart_write( char *text)
{   
    uint8_t i;
    
    for(i=0; i<strlen(text);i++)
    {
       usart_transmit(text[i]);
       if(text[i] == '\n') //add carriage return
       {
           usart_transmit(015);
       }
    }
}

void usart_writeln( char *text)
{
    uint8_t i;
    
    for(i=0; i<strlen(text);i++)
    {
       usart_transmit(text[i]);
    }
    
    //new line and carriage return
    usart_transmit(012);
    usart_transmit(015);
}

void usart_write_hexln(unsigned int c)
{
    uint8_t i;
    char hex[17];
    
    sprintf(hex, "%X", c);
    
    for(i=0; i<strlen(hex);i++)
    {
       usart_transmit(hex[i]);
    }
    
    //new line and carriage return
    usart_transmit(012);
    usart_transmit(015);
}


unsigned char usart_read(void)
{
    // Wait for data to be received
    while ( !(UCSRA & (1<<RXC)) );
    
    uint8_t c = UDR;
    // echo to terminal if character
    if(usart_echo)
    {
        if (c >= 32 && c <= 126)
        {
        usart_transmit(c);
        }
        //end of line
        else if (10)
        {
            usart_writeln("");
        }
    }
    return c;
}

char* usart_readln()
{
    usart_readln_start();
    while(usart_readline);
    return usart_buffer;
}

//clear read buffer
void usart_readln_start(void)
{
    memset(usart_buffer, 0, USART_BUFFER_SIZE);
    usart_buffer_index = 0;
    usart_readline = 1;
}

void usart_readln_ready()
{
    usart_readline = 0;
    //TODO add some stuff to send it forward
}
    
    
    
